/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package JavaFiler;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author Per Stian Hoff & Gjerde
 */
@Named("result")
@SessionScoped
public class ResultBean implements Serializable,Constants {
    
    private boolean minus=false;
    private boolean multiply=false;
    private boolean divide=false;
    private int tryPlus,plusScore,tryMinus,minusScore,tryMultiply,multiplyScore,tryDivide,divideScore=0;
    dbConnection dbCon = new dbConnection();
    private String name;
    private User showHighScoreUser;
    private ArrayList<User> plusList;
    private ArrayList<User> minusList;
    private ArrayList<User> multiplyList;
    private ArrayList<User> divideList;

    //Gets the username of the logged in user.
    private void getUserData() {
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        Object requestObject = context.getRequest();
        if (!(requestObject instanceof HttpServletRequest)) {
            return;
        }
        HttpServletRequest request = (HttpServletRequest) requestObject;
        name = request.getRemoteUser();
    }

    public String getUsername() {
        if (name == null) {
            getUserData();
        }
        return name == null ? "" : name;
    }
    public String getName(){
        return name;
    }
    //This method is used in the JUnit tests.
    public void setName(String name){
        this.name = name;
    }
    //Find the role of the user witch is logged inn.
     public Boolean findRole() {
        boolean check = false;
        if (getRole().equals("system")) {
            check = true;
        }
        return check;
    }

    public String getRole() {

        return isInRole("bruker") ? "bruker" : "system";
    }
    //Gets role data.
    public boolean isInRole(String role) {
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        Object requestObject = context.getRequest();
        if (!(requestObject instanceof HttpServletRequest)) {
            return false;
        }
        HttpServletRequest request = (HttpServletRequest) requestObject;
        return request.isUserInRole(role);
    }

    public boolean isDivide() {
        return divide;
    }

    public void setDivide(boolean divide) {
        this.divide = divide;
    }

    public boolean isMultiply() {
        return multiply;
    }

    public void setMultiply(boolean gange) {
        this.multiply = gange;
    }

    public boolean isMinus() {
        setUnlock();
        return minus;
    }
    //This method unlocks the rooms that is opened.
    public void setUnlock(){
    if(findRole()){
            minus=true;
            multiply=true;
            divide=true;
        }
        setStatsThisUser();
        if(plusScore>=SCOREREQ){
           minus=true;
        }else if(minusScore>=SCOREREQ){
           multiply=true;
        }else if(multiplyScore>=SCOREREQ){
           divide=true;
        }
    }

    public void setMinus(boolean minus) {
        this.minus = minus;
    }
    //Gets the stats of a chosen user. Gets data from the DB.
     public void setStats(User user) {
        Connection connection = dbCon.getCon();
        String username = user.getUsername();
        if(showHighScoreUser==null){
            showHighScoreUser = new User();
        }
        showHighScoreUser=user;
        try {
            PreparedStatement prep3 = connection.prepareStatement("Select * from spillarkiv WHERE brukernavn=?");
            prep3.setString(1, username);
            ResultSet res3 = prep3.executeQuery();

            try {
                while (res3.next()) {
                        tryPlus = res3.getInt("forsok_pluss");
                        plusScore = res3.getInt("pluss_score");
                        tryMinus =res3.getInt("forsok_minus");
                        minusScore =res3.getInt("minus_score");
                        tryMultiply =res3.getInt("forsok_gange");
                        multiplyScore =res3.getInt("gange_score");
                        tryDivide =res3.getInt("forsok_deling");
                        divideScore =res3.getInt("deling_score");

                }
                res3.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbCon.disconnect();
        }
    }
    //Gets the stats of a logged in user. Gets data from the DB.
     public void setStatsThisUser() {
        Connection connection = dbCon.getCon();
        String username = getUsername();
        
        try {
            PreparedStatement prep3 = connection.prepareStatement("Select * from spillarkiv WHERE brukernavn=?");
            prep3.setString(1, username);
            ResultSet res3 = prep3.executeQuery();

            try {
                while (res3.next()) {
                        tryPlus = res3.getInt("forsok_pluss");
                        plusScore = res3.getInt("pluss_score");
                        tryMinus =res3.getInt("forsok_minus");
                        minusScore =res3.getInt("minus_score");
                        tryMultiply =res3.getInt("forsok_gange");
                        multiplyScore =res3.getInt("gange_score");
                        tryDivide =res3.getInt("forsok_deling");
                        divideScore =res3.getInt("deling_score");

                }
                res3.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbCon.disconnect();
        }
    }

    public int getDivideScore() {
        return divideScore;
    }

    public int getTryDivide() {
        return tryDivide;
    }

    public int getTryMultiply() {
        return tryMultiply;
    }

    public int getTryMinus() {
        return tryMinus;
    }

    public int getTryPlus() {
        return tryPlus;
    }

    public int getMultiplyScore() {
        return multiplyScore;
    }

    public int getMinusScore() {
        return minusScore;
    }

    public int getPlusScore() {
        return plusScore;
    }

    public User getShowHighScoreUser() {
        return showHighScoreUser;
    }
    //Higscore from all the users for the plus room.
    public ArrayList<User> getTableScorePlus()throws SQLException{
        if(plusList == null){
            plusList = new ArrayList<User>();
        }
        getPlusScoreFromDB();
        return plusList;
    }
    //Higscore from all the users for the minus room.
    public ArrayList<User> getTableScoreMinus()throws SQLException{
        if(minusList == null){
            minusList = new ArrayList<User>();
        }
        getMinusScoreFromDB();
        return minusList;
    }
    //Higscore from all the users for the multiply room.
    public ArrayList<User> getTableScoreMultiply()throws SQLException{
        if(multiplyList == null){
            multiplyList = new ArrayList<User>();
        }
        getMultiplyScoreFromDB();
        return multiplyList;
    }
    //Higscore from all the users for the divide room.
    public ArrayList<User> getTableScoreDivide()throws SQLException{
        if(divideList == null){
            divideList = new ArrayList<User>();
        }
        getDivideScoreFromDB();
        return divideList;
    }
    //Gets score from DB
     synchronized private void getPlusScoreFromDB() throws SQLException{
        plusList.clear();
        Connection connection = dbCon.getCon();
        try {
            PreparedStatement prep3 = connection.prepareStatement("select * from spillarkiv order by pluss_score desc");
            ResultSet res3 = prep3.executeQuery();
            try {
                while (res3.next()) {

                        plusList.add(new User(res3.getString("brukernavn"),
                                res3.getInt("pluss_score")));
                }
                res3.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbCon.disconnect();
        }
    }
    //Gets score from DB
     synchronized private void getMinusScoreFromDB() throws SQLException{
        minusList.clear();
        Connection connection = dbCon.getCon();
        try {
            PreparedStatement prep3 = connection.prepareStatement("select * from spillarkiv order by minus_score desc");
            ResultSet res3 = prep3.executeQuery();
            try {
                while (res3.next()) {
                        minusList.add(new User(res3.getString("brukernavn"),
                                res3.getInt("minus_score")));
                }
                res3.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbCon.disconnect();
        }
    }
    //Gets score from DB
     synchronized private void getMultiplyScoreFromDB() throws SQLException{
        multiplyList.clear();
        Connection connection = dbCon.getCon();
        try {
            PreparedStatement prep3 = connection.prepareStatement("select * from spillarkiv order by gange_score desc");
            ResultSet res3 = prep3.executeQuery();
            try {
                while (res3.next()) {
                        multiplyList.add(new User(res3.getString("brukernavn"),
                                res3.getInt("gange_score")));
                }
                res3.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbCon.disconnect();
        }
    }
    //Gets score from DB
     synchronized private void getDivideScoreFromDB() throws SQLException{
        divideList.clear();
        Connection connection = dbCon.getCon();
        try {
            PreparedStatement prep3 = connection.prepareStatement("select * from spillarkiv order by deling_score desc");
            ResultSet res3 = prep3.executeQuery();
            try {
                while (res3.next()) {
                        divideList.add(new User(res3.getString("brukernavn"),
                                res3.getInt("deling_score")));
                }
                res3.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbCon.disconnect();
        }
    }
}